import {useAppStore} from "../../store";
import {Communication} from "../Communication";

export class WebSocketClient {
    constructor(url, name, reconnectInterval) {
        this.name = name
        this.url = url;
        this.reconnectInterval = reconnectInterval;
        this.instance = null;
        this.store = null
        this.lock = false
    }

    connect() {
        this.store= useAppStore()
        this.instance = new WebSocket(this.url);
        this.instance.onopen = () => {
            this.store.changeState(this.name,true)
            this.onOpen()
        }
        this.instance.onmessage = (data) => {
            this.onMessage(JSON.parse(data.data))
        }
        this.instance.onerror = (error) => {
            this.onError(error)
            this.store.changeState(this.name,false)
            this.reconnect()
        };
        this.instance.onclose = (event) => {
            this.onClose(event)
            this.store.changeState(this.name,false)
            this.reconnect()
        };
    }

    reconnect() {
        if (this.lock) return;
        this.lock = true;
        setTimeout( ()=> {
            this.connect();
            this.lock = false;
        }, this.reconnectInterval);
    }

    sendMessage(data) {
        if (this.instance.readyState === WebSocket.OPEN) {
            console.log("发送消息：" + data)
            this.instance.send(JSON.stringify(data))
        }else {
            console.log("未连接"+this.name+"，消息无法发送："+JSON.stringify(data))
        }
    }

    onOpen() {

    }

    onMessage(data) {

    }

    onError(error) {

    }

    onClose(event) {

    }
    send(data){

    }
}
